package com.wyt.Filter;

import com.mysql.cj.Session;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: book
 * @description: 登录拦截器
 * @author: 王一同
 * @create: 2021-11-30 09:54
 **/
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("开启拦截");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        if (uri.contains("login") || uri.contains("login.jsp") || uri.contains("layui")) {//直接放行登录页面，注册页面
            chain.doFilter(req, resp);
        } else {
            HttpSession session = req.getSession();
            Object emp = session.getAttribute("login");
            if (emp == null) {
                resp.sendRedirect("/login.jsp");
            } else {
                chain.doFilter(req, resp);
            }
        }

    }

    @Override
    public void destroy() {
        System.out.println("拦截结束");
    }
}
